package com.haitaoit.chengquan.module.center.activity.order;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.RelativeSizeSpan;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.haitaoit.chengquan.R;
import com.haitaoit.chengquan.base.BackCall;
import com.haitaoit.chengquan.base.BaseActivity;
import com.haitaoit.chengquan.module.car.activity.OrderPayActivity;
import com.haitaoit.chengquan.module.center.activity.return_goods.ApplyReturnActivity;
import com.haitaoit.chengquan.module.center.activity.return_goods.BackReturnActivity;
import com.haitaoit.chengquan.module.center.activity.return_goods.PlyReturnActivity;
import com.haitaoit.chengquan.module.center.activity.yuyue.MyBuyEvaluateActivity;
import com.haitaoit.chengquan.module.center.activity.yuyue.SendEvaluateActivity;
import com.haitaoit.chengquan.module.center.adapter.order.MyOrderDetailAdapter;
import com.haitaoit.chengquan.module.center.model.MyOrderDetailModel;
import com.haitaoit.chengquan.module.center.model.MyOrderDetailModel3;
import com.haitaoit.chengquan.utils.Constant;
import com.haitaoit.chengquan.utils.DialogUtil;
import com.haitaoit.chengquan.utils.GetSign;
import com.haitaoit.chengquan.utils.HttpUtilsSingle;
import com.haitaoit.chengquan.utils.NameValuePairSign;
import com.haitaoit.chengquan.utils.PreferenceUtils;
import com.haitaoit.chengquan.utils.ToastUtils;
import com.haitaoit.chengquan.utils.Utils;
import com.haitaoit.chengquan.view.MyListView;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.tencent.connect.auth.QQAuth;
import com.tencent.open.wpa.WPA;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class MyOrderDetailActivity extends BaseActivity {
    @ViewInject(R.id.wuliu_ll)
    LinearLayout wuliu_ll;
    //    @ViewInject(R.id.address_img)
    //    ImageView address_img;
    @ViewInject(R.id.scrollview_listview)
    MyListView   listView;
    @ViewInject(R.id.order_detail_price)
    TextView     order_detail_price;
    @ViewInject(R.id.detail_state)
    TextView     detail_state;

    @ViewInject(R.id.cancel_order)
    TextView cancel_order;
    @ViewInject(R.id.go_pay)
    TextView go_pay;
    @ViewInject(R.id.apply_refund)
    TextView apply_refund;
    @ViewInject(R.id.remind_goods)
    TextView remind_goods;
    @ViewInject(R.id.check_wuliu)
    TextView check_wuliu;
    @ViewInject(R.id.confirm_complete)
    TextView confirm_complete;
    @ViewInject(R.id.apply_return_goods)
    TextView apply_return_goods;
    @ViewInject(R.id.apply_change_goods)
    TextView apply_change_goods;
    //    @ViewInject(R.id.go_eva)
    //    TextView go_eva;
    @ViewInject(R.id.detele_order)
    TextView detele_order;
    @ViewInject(R.id.order_add_name)
    TextView order_add_name;
    @ViewInject(R.id.order_add_phone)
    TextView order_add_phone;
    @ViewInject(R.id.order_add_detail)
    TextView order_add_detail;
    @ViewInject(R.id.order_kuaidi)
    TextView order_kuaidi;
    @ViewInject(R.id.order_preferential_amount)
    TextView order_preferential_amount;
    @ViewInject(R.id.order_amount)
    TextView order_amount;
    @ViewInject(R.id.order_no_tv)
    TextView order_no_tv;
    @ViewInject(R.id.addtime)
    TextView addtime;
    @ViewInject(R.id.go_eva)
    TextView go_eva;
    @ViewInject(R.id.confirm_time)
    TextView confirm_time;
    @ViewInject(R.id.logistics_time)
    TextView logistics_time;
    @ViewInject(R.id.receiving_time)
    TextView receiving_time;
    @ViewInject(R.id.invoice_looked_up)
    TextView invoice_looked_up;
    @ViewInject(R.id.user_remark)
    TextView user_remark;


    private Dialog               dlg;
    private MyOrderDetailAdapter adapter;
    private String               order_no;
    private MyOrderDetailModel   model;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView_V(R.layout.activity_my_order_detail);
        setTitle_V("订单详情");
        setLeftShow(1, R.mipmap.left);
        backLeft_V();
        ViewUtils.inject(this);


        adapter = new MyOrderDetailAdapter(this);
        adapter.setStatus("1");
        adapter.setBackCall(backCall);
        listView.setAdapter(adapter);

        order_no = getIntent().getStringExtra("order_no");
    }

    @Override
    protected void onResume() {
        httpGetorder_model();
        super.onResume();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 23 && resultCode == 1) {
            finish();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    BackCall backCall = new BackCall() {
        @Override
        public void deal(int which, Object... obj) {
            int position = (Integer) obj[0];
            switch (which) {
                case R.id.go_item_eva:// 去评价
                    Intent intent = new Intent(MyOrderDetailActivity.this, SendEvaluateActivity.class);
                    intent.putExtra("order_no", order_no);
                    intent.putExtra("order_goods_id", model.getList_goods().get(position).getOrder_goods_id());
                    intent.putExtra("circleimage_uri_goods", model.getList_goods().get(position).getImg_url());
                    startActivity(intent);
                    break;
            }
            super.deal(which, obj);
        }
    };

    @OnClick({R.id.wuliu_ll, R.id.address_ll, R.id.cancel_order, R.id.go_pay,
            R.id.remind_goods, R.id.check_wuliu, R.id.confirm_complete, R.id.apply_return_goods,
            R.id.apply_refund, R.id.apply_change_goods, R.id.go_eva, R.id.detele_order, R.id.maijiaQQ,})
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.address_ll:// 未付款时 换地址
                //                if ("nopay".equals(getIntent().getStringExtra("order_type"))) {
                //                    intent.setClass(MyOrderDetailActivity.this, MyAddressActivity.class);
                //                    startActivity(intent);  }
                break;
            case R.id.cancel_order:// 取消订单
                dlg = DialogUtil.showInfoDialog1(MyOrderDetailActivity.this, "提示",
                        "您确定要取消该订单吗？", "确定取消", "再想想", new BackCall() {
                            public void deal(int which, Object... obj) {
                                switch (which) {
                                    case R.id.confirm:// 确定
                                        httpGetcancel_order();
                                        break;
                                }
                                super.deal(which);
                            }
                        });
                dlg.setCanceledOnTouchOutside(true);
                dlg.show();
                break;
            case R.id.go_pay:// 付款
                intent.setClass(MyOrderDetailActivity.this, OrderPayActivity.class);
                intent.putExtra("order_no", order_no);
                intent.putExtra("order_amount", model.getOrder_amount());
                startActivity(intent);
                break;
            case R.id.remind_goods:// 提醒发货
                httpGetshipment_remind();
                break;
            case R.id.wuliu_ll:
            case R.id.check_wuliu:// 查看物流
                intent.setClass(MyOrderDetailActivity.this, TransportStateActivity.class);
                intent.putExtra("order_no", order_no);
                startActivity(intent);
                //        Uri uri = Uri.parse("http://google.com");
                //        Intent it = new Intent(Intent.ACTION_VIEW, uri);
                //        startActivity(it);
                break;
            case R.id.confirm_complete:// 确认收货
                dlg = DialogUtil.showInfoDialog1(MyOrderDetailActivity.this, "提示",
                        "确认收货？", "确定", "还没有", new BackCall() {
                            public void deal(int which, Object... obj) {
                                switch (which) {
                                    case R.id.confirm:// 确定
                                        httpGetreceiving_order();
                                        break;
                                }
                                super.deal(which);
                            }
                        });
                dlg.setCanceledOnTouchOutside(true);
                dlg.show();
                break;
            case R.id.apply_return_goods:// 申请退货
                intent.setClass(MyOrderDetailActivity.this, BackReturnActivity.class);
                intent.putExtra("order_no", order_no);
                intent.putExtra("amount", model.getOrder_amount());
                intent.putExtra("again", "1");
                startActivityForResult(intent, 23);
                break;
            case R.id.apply_refund:// 申请退款
                intent.setClass(MyOrderDetailActivity.this, PlyReturnActivity.class);
                intent.putExtra("order_no", order_no);
                intent.putExtra("amount", model.getOrder_amount());
                intent.putExtra("again", "1");
                startActivityForResult(intent, 23);
                break;
            case R.id.apply_change_goods:// 申请换货
                intent.setClass(MyOrderDetailActivity.this, ApplyReturnActivity.class);
                intent.putExtra("order_no", order_no);
                intent.putExtra("amount", model.getOrder_amount());
                intent.putExtra("again", "1");
                startActivityForResult(intent, 23);
                break;
            case R.id.go_eva:// 评价

                if (model == null || model.getList_goods() == null) {

                    return;
                }
                List<MyOrderDetailModel3> list_goods = model.getList_goods();
                intent.setClass(MyOrderDetailActivity.this, MyBuyEvaluateActivity.class);
                intent.putExtra("order_no", order_no);
                intent.putExtra("order_goods_id", list_goods.get(0).getOrder_goods_id());
                intent.putExtra("image_uri", list_goods.get(0).getImg_url());
                startActivity(intent);
                break;
            case R.id.detele_order:
                dlg = DialogUtil.showInfoDialog1(MyOrderDetailActivity.this, "提示",
                        "您确定要删除该订单吗？", "确定", "取消", new BackCall() {
                            public void deal(int which, Object... obj) {
                                switch (which) {
                                    case R.id.confirm:// 确定
                                        httpGetdel_order();
                                        break;
                                }
                                super.deal(which);
                            }
                        });
                dlg.setCanceledOnTouchOutside(true);
                dlg.show();
                break;
            case R.id.maijiaQQ:
                if (model.getQq().equals("")) {
                    ToastUtils.showToast("该卖家没有填写QQ！");
                } else {
                    QQAuth mqqAuth = QQAuth.createInstance("1105935142", this);// 10000000为你申请的APP_ID,mContext是上下文
                    WPA mWPA = new WPA(this, mqqAuth.getQQToken());
                    int ret = mWPA.startWPAConversation(this, model.getQq(), "你好");//客服QQ
                    if (ret != 0) {// 如果ret不为0，就说明调用SDK出现了错误
                        ToastUtils.showToast("抱歉，联系客服出现了错误~. error:" + ret);
                    }
                }
                break;
        }
        super.onClick(v);
    }

    public void setvisiable() {
        cancel_order.setVisibility(View.GONE);
        go_pay.setVisibility(View.GONE);
        apply_refund.setVisibility(View.GONE);
        remind_goods.setVisibility(View.GONE);
        check_wuliu.setVisibility(View.GONE);
        confirm_complete.setVisibility(View.GONE);
        apply_return_goods.setVisibility(View.GONE);
        apply_change_goods.setVisibility(View.GONE);
        //        go_eva.setVisibility(View.GONE);

        confirm_time.setVisibility(View.VISIBLE);
        logistics_time.setVisibility(View.VISIBLE);
        receiving_time.setVisibility(View.VISIBLE);
    }

    // 我的订单详细
    private void httpGetorder_model() {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));
        list.add(new NameValuePairSign("order_no", order_no));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("user_id", PreferenceUtils.getPrefString("user_id", ""));
        params.addQueryStringParameter("order_no", order_no);
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, Constant.Getorder_model, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String jsonString = arg0.result.toString();
                JSONObject json;
                try {
                    json = new JSONObject(jsonString);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            return;
                        case 0:// 成功
                            model = gson.fromJson(Response, MyOrderDetailModel.class);
                            //                            status: 订单状态(1待付款显示取消订单和去付款 2待发货显示申请退款和提醒发货
                            //                                    3待收货显示查看物流和确认收货 4待评价显示申请退货和申请换货和评价
                            //                                    5交易成功显示申请退货和申请换货和删除订单)
                            setvisiable();
                            if (model.getStatus().equals("1")) {
                                wuliu_ll.setVisibility(View.GONE);
                                detail_state.setText("待付款");
                                cancel_order.setVisibility(View.VISIBLE);
                                go_pay.setVisibility(View.VISIBLE);
                                confirm_time.setVisibility(View.GONE);
                                logistics_time.setVisibility(View.GONE);
                                receiving_time.setVisibility(View.GONE);
                            } else if (model.getStatus().equals("2")) {
                                wuliu_ll.setVisibility(View.GONE);
                                //                                address_img.setVisibility(View.GONE);
                                detail_state.setText("待发货");
                                apply_refund.setVisibility(View.VISIBLE);
                                remind_goods.setVisibility(View.VISIBLE);
                                logistics_time.setVisibility(View.GONE);
                                receiving_time.setVisibility(View.GONE);
                            } else if (model.getStatus().equals("3")) {
                                //                                address_img.setVisibility(View.GONE);
                                detail_state.setText("待收货");
                                check_wuliu.setVisibility(View.VISIBLE);
                                confirm_complete.setVisibility(View.VISIBLE);
                                receiving_time.setVisibility(View.GONE);
                            } else if (model.getStatus().equals("4")) {
                                //                                address_img.setVisibility(View.GONE);
                                detail_state.setText("待评价");
                                apply_return_goods.setVisibility(View.VISIBLE);
                                apply_change_goods.setVisibility(View.VISIBLE);
                                go_eva.setVisibility(View.VISIBLE);
                            } else if (model.getStatus().equals("5")) {
                                //                                address_img.setVisibility(View.GONE);
                                detail_state.setText("已完成");
                                apply_return_goods.setVisibility(View.VISIBLE);
                                apply_change_goods.setVisibility(View.VISIBLE);
                                detele_order.setVisibility(View.VISIBLE);
                            } else if (model.getStatus().equals("")) {
                                ToastUtils.showToast("该订单信息有误，请重新刷新列表！");
                            }
                            wuliu_ll.setVisibility(View.GONE);

                            order_add_name.setText("收货人：" + model.getAddress_model().getAccept_name());
                            order_add_phone.setText(model.getAddress_model().getTelphone());
                            order_add_detail.setText("收货地址：" + model.getAddress_model().getAddress());
                            order_kuaidi.setText("¥ " + model.getOrder_logistics_money());
                            order_preferential_amount.setText("-¥ " + model.getOrder_preferential_amount());

                            order_amount.setText("¥ " + Utils.format(Float.valueOf(model.getOrder_amount())
                                    + Float.valueOf(model.getOrder_preferential_amount())));
                            // 部分字体变大变色
                            SpannableString msp = new SpannableString("¥ " + model.getOrder_amount());
                            msp.setSpan(new RelativeSizeSpan(1.5f), 1, ("¥ " + model.getOrder_amount()).length(),
                                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                            order_detail_price.setText(msp);
                            if (model.getUser_remark().equals("")) {
                                user_remark.setText("备注信息：无");
                            } else {
                                user_remark.setText("备注信息：" + model.getUser_remark());
                            }
                            if (model.getInvoice_looked_up().equals("")) {
                                invoice_looked_up.setText("发票抬头：无");
                            } else {
                                invoice_looked_up.setText("发票抬头：" + model.getInvoice_looked_up());
                            }
                            adapter.setStatus(model.getStatus());
                            adapter.setList(model.getList_goods());
                            adapter.notifyDataSetChanged();

                            order_no_tv.setText("订单号：" + model.getOrder_no());
                            addtime.setText("创建时间：" + model.getAddtime());
                            confirm_time.setText("付款时间：" + model.getConfirm_time());
                            logistics_time.setText("发货时间：" + model.getLogistics_time());
                            receiving_time.setText("收货时间：" + model.getReceiving_time());
                            return;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    // 取消订单
    private void httpGetcancel_order() {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));
        list.add(new NameValuePairSign("order_no", order_no));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("user_id", PreferenceUtils.getPrefString("user_id", ""));
        params.addQueryStringParameter("order_no", order_no);
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, Constant.Getcancel_order, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String jsonString = arg0.result.toString();
                JSONObject json;
                try {
                    json = new JSONObject(jsonString);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            return;
                        case 0:// 成功
                            ToastUtils.showToast(Errmsg);
                            finish();
                            return;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    // 提醒发货
    private void httpGetshipment_remind() {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));
        list.add(new NameValuePairSign("order_no", order_no));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("user_id", PreferenceUtils.getPrefString("user_id", ""));
        params.addQueryStringParameter("order_no", order_no);
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, Constant.Getshipment_remind, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String jsonString = arg0.result.toString();
                JSONObject json;
                try {
                    json = new JSONObject(jsonString);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            return;
                        case 0:// 成功
                            ToastUtils.showToast(Errmsg);
                            return;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    // 删除订单
    private void httpGetdel_order() {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));
        list.add(new NameValuePairSign("order_no", order_no));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("user_id", PreferenceUtils.getPrefString("user_id", ""));
        params.addQueryStringParameter("order_no", order_no);
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, Constant.Getdel_order, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String jsonString = arg0.result.toString();
                JSONObject json;
                try {
                    json = new JSONObject(jsonString);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            return;
                        case 0:// 成功
                            ToastUtils.showToast(Errmsg);
                            finish();
                            return;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    // 确认收货订单
    private void httpGetreceiving_order() {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));
        list.add(new NameValuePairSign("order_no", order_no));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("user_id", PreferenceUtils.getPrefString("user_id", ""));
        params.addQueryStringParameter("order_no", order_no);
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, Constant.Getreceiving_order, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String jsonString = arg0.result.toString();
                JSONObject json;
                try {
                    json = new JSONObject(jsonString);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            return;
                        case 0:// 成功
                            ToastUtils.showToast(Errmsg);
                            httpGetorder_model();
                            return;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }
}
